package com.lq.ecoldchain.util

import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.entity.EventAll
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.*


/*
*2019/1/16 0016  17:04
*高德地图工具 by lq
*/
object AMapUtils {
    private val locationClient by lazy { AMapLocationClient(App.instance) }
    private val locationOption by lazy { AMapLocationClientOption() }
    private val format by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA) }
    fun location() {
//        locationOption.interval = 1000 * 3//三秒钟定位一次
        locationOption.interval = 1000 * 60 * 30//半小时定位一次
        locationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        locationClient.setLocationListener {
            if (it != null) {
                if (it.errorCode == 0) {
                    val city = it.city.replace("市","")
                    logi { "定位成功:$city" }
                    if (city.isNotEmpty())
                        EventBus.getDefault().post(EventAll.LocationChangeEvent(city))
                } else {
                    logw { "location Error, Time:${format.format(it.time)}, ErrCode:" + it.errorCode + ", errInfo:" + it.errorInfo }
                }
            }
        }
        locationClient.setLocationOption(locationOption)
        locationClient.startLocation()
    }
}